/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package harlequin;


import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;


/**
 *
 * @author Samsung
 */
public class SQLDataAdder {
    
    private PreparedStatement pstmt;
    private StringBuilder statement;

    public SQLDataAdder() {
        if(!Connector.isConnected())
            Connector.connect();
    }
    
    public SQLDataAdder addTable(String tableName){
        statement = new StringBuilder();
        statement.append("INSERT INTO ");
        statement.append(tableName);
        statement.append(" (");
        return this;
    }
    
    public SQLDataAdder addFields(String... fields){
        
        for(int i = 0; i<fields.length; i++){
            statement.append(fields[i]);
            if(i < fields.length-1)
                statement.append(",");
            else
                statement.append(")");
        }
        statement.append(" VALUES (");
       return this;
   
    }
     
    
    public SQLDataAdder addValues(Object... values){
        try {
            for(int i = 0; i<values.length; i++){
                    statement.append("?");
                    if(i < values.length-1)
                        statement.append(",");
                    else
                        statement.append(")");
            }

            pstmt = Connector.getConnector()
                                .prepareStatement(statement.toString());

            for(int i = 0; i<values.length; i++){
                pstmt.setObject(i+1, values[i]);
            }
            
        } catch (SQLException ex) {
            Logger.getLogger(SQLDataAdder.class.getName())
                    .log(Level.SEVERE, null, ex);
     
             
        }
        
        return this;
    }
    
    public boolean addToDatabase() {
        
        try {
            System.out.println(pstmt);
            pstmt.executeUpdate();
            pstmt.close();
            return true;
            
        } catch (Exception ex) {
              
            Logger.getLogger(SQLDataAdder.class.getName())
                    .log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null,"Input Error: Invalid or Duplicate entry");
            return false;
        }
        
    }
}
